package com.lvmama.rhino.utils;

import java.io.BufferedWriter;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

public class ExportCSVUtils<T> {
    public boolean exportCSV(String[] headers,Field[] fields, Collection<T> dataset, BufferedWriter bf,
        String pattern) throws Exception {
        for(String str : headers){
            bf.write(str+",");
        }
        bf.newLine();
        
        // 遍历集合数据，产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            T t = (T) it.next();
            // 利用反射，根据javabean属性的先后顺序，动态调用getXxx()方法得到属性值
            //Field[] fields = t.getClass().getDeclaredFields();
            Field field = null;
            String fieldName = null;
            String getMethodName = null;
            Class tCls = null;
            Method getMethod = null;
            Object value = null;
            Date date = null;
            SimpleDateFormat sdf = null;
            String textValue = null;
            for (short i = 0; i < fields.length; i++) {
                field = fields[i];
                fieldName = field.getName();
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[] {});
                    value = getMethod.invoke(t, new Object[] {});
                    // 判断值的类型后进行强制类型转换
                    if(value ==null){
                        continue;
                    }else if (value instanceof Date) {
                        date = (Date) value;
                        sdf = new SimpleDateFormat(pattern);
                        textValue = sdf.format(date);
                    }
                    else {
                        // 其它数据类型都当作字符串简单处理
                        textValue = value.toString();
                    }
                    // 如果不是图片数据，就利用正则表达式判断textValue是否全部由数字组成
                    if (textValue != null) {
                        bf.write(textValue+",");
                    }
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
                finally {
                    // 清理资源
                }
            }
            if (it.hasNext()) {
                bf.newLine();
            }
        }
        bf.flush();
        bf.close();
        return false;
    }
}
